require 'rubygems'
require 'sinatra'
require 'erb'

configure do
  LOGGER = Logger.new("/home/cache/sinatra.log") 
end
 
helpers do
  def logger
    LOGGER
  end
end

get '/hi' do
  "Hello World!"
end

get '/' do
  erb :index
end

# rasterisation of a given SVG document via a given XSL transform
get '/rasterize/*/via/*' do |uri|
  
  puts "rasterize via xslt"

  uri = 'http://'+params[:splat][0]
  via = 'http://'+params[:splat][1]
    
  # create new SVG document
  svg = VeeGee.new uri

  # transform the svg document
  xsl = Saxon.new via
  x = xsl.transform uri, params, "/home/cache/#{svg.cacheKey}.svg"

  # set the svg uri to the transformed xsl & render it
  svg.uri = 'file://' + File.expand_path("/home/cache/#{svg.cacheKey}.svg")
  svg.render "/home/cache/#{svg.cacheKey}.png"

  # read cached image 
  contents = open("/home/cache/#{svg.cacheKey}.png", "rb") {|io| io.read }

  # output
  content_type 'image/png'
  contents
  
end
  
# simple rasterisation of a given SVG document
get '/rasterize/*' do |uri|

  puts "rasterize"

  logger.info uri
  logger.info "sinatra"
  svg = VeeGee.new('http://'+uri)
  logger.info("#{svg.cacheKey}")
  svg.render("/home/cache/#{svg.cacheKey}.png")

  # read cached image 
  contents = open("/home/cache/#{svg.cacheKey}.png", "rb") {|io| io.read }

  # output
  content_type 'image/png'
  contents
end

# returns the key used to cache the rasterized SVG 
get '/key/*' do |uri|
  svg = VeeGee.new uri
  content_type 'text/plain'
  svg.cacheKey 
end





